import { ref, computed, onMounted } from 'vue'
import { loadBlogPosts, getBlogStats, filterBlogPosts } from './BlogUtils'
import type { BlogPost, BlogStats, BlogFilters } from './BlogTypes'

export const useBlog = () => {
  const posts = ref<BlogPost[]>([])
  const loading = ref(true)
  const error = ref<string | null>(null)
  
  const filters = ref<BlogFilters>({
    tag: undefined,
    search: '',
    sortBy: 'date',
    sortOrder: 'desc'
  })
  
  const selectedPost = ref<BlogPost | null>(null)
  const showDetail = ref(false)
  
  // 计算属性
  const filteredPosts = computed(() => {
    let filtered = filterBlogPosts(posts.value, {
      tag: filters.value.tag,
      search: filters.value.search
    })
    
    // 排序
    filtered = [...filtered].sort((a, b) => {
      let comparison = 0
      
      if (filters.value.sortBy === 'date') {
        comparison = new Date(a.date).getTime() - new Date(b.date).getTime()
      } else if (filters.value.sortBy === 'title') {
        comparison = a.title.localeCompare(b.title)
      }
      
      return filters.value.sortOrder === 'desc' ? -comparison : comparison
    })
    
    return filtered
  })
  
  const stats = computed(() => getBlogStats(posts.value))
  
  const allTags = computed(() => {
    const tags = new Set<string>()
    posts.value.forEach(post => {
      post.tags.forEach(tag => tags.add(tag))
    })
    return Array.from(tags).sort()
  })
  
  // 方法
  const loadPosts = async () => {
    try {
      loading.value = true
      error.value = null
      posts.value = await loadBlogPosts()
    } catch (err) {
      error.value = 'Failed to load blog posts'
      console.error('Error loading posts:', err)
    } finally {
      loading.value = false
    }
  }
  
  const setFilter = (newFilters: Partial<BlogFilters>) => {
    filters.value = { ...filters.value, ...newFilters }
  }
  
  const clearFilters = () => {
    filters.value = {
      tag: undefined,
      search: '',
      sortBy: 'date',
      sortOrder: 'desc'
    }
  }
  
  const viewPost = (post: BlogPost) => {
    selectedPost.value = post
    showDetail.value = true
  }
  
  const closeDetail = () => {
    showDetail.value = false
    selectedPost.value = null
  }
  
  // 生命周期
  onMounted(() => {
    loadPosts()
  })
  
  return {
    // 状态
    posts,
    loading,
    error,
    filters,
    selectedPost,
    showDetail,
    
    // 计算属性
    filteredPosts,
    stats,
    allTags,
    
    // 方法
    loadPosts,
    setFilter,
    clearFilters,
    viewPost,
    closeDetail
  }
}